package com.pdd.controller;

import com.pdd.beans.Admin;
import com.pdd.dto.DTO;
import com.pdd.service.AdminService;
import com.pdd.util.EncryptUtil;
import com.pdd.util.IPUtil;
import com.pdd.vo.admin.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api(description = "管理员相关接口",tags = {"管理员登录接口"})
@Controller
public class AdminController {

    @Autowired
    @Setter
    private AdminService adminService;

    @ApiOperation(value = "登录操作")
    @RequestMapping(value = "/admin/login", method = RequestMethod.POST)
    @ResponseBody
    public DTO login(@RequestBody AdminLoginVO vo, HttpServletRequest request) {
        // 1. 验证邮箱是否存在
        Admin result = adminService.getByEmail(vo.getEmail());
        if (result == null) {
            return new DTO(2001, "邮箱账号不存在");
        }

        // 2. 验证密码是否正确
        String pwd = EncryptUtil.getMD5(vo.getPwd());
        if (!result.getPwd().equals(pwd)){
            return new DTO(2002, "密码错误");
        }

        // 3. 更新登录信息
        Admin admin = new Admin();
        admin.setEmail(result.getEmail());  // 邮箱
        admin.setLastLoginTime(new Date()); // 当前时间
        admin.setLastLoginIp(IPUtil.getRealIP(request));    // IP地址
        adminService.update(admin);

        return new DTO<Admin>(1000, "登录成功", result);
    }

}
